from fastapi import FastAPI,staticfiles
from fastapi.exceptions import RequestValidationError
from fastapi.responses import PlainTextResponse
from starlette.exceptions import HTTPException as StarletteHTTPException
import uvicorn

from src.tutorial import app01,app02,app03,app04,app05,app06,app07


app = FastAPI(
    title="FastAPI tutorial notes",
    description="《FastAPI指南》学习笔记",
    version="1.0.0",
    docs_url="/docs",
    redoc_url="/redocs"
)

#挂载静态资源   pip3 install aiofiles
app.mount(path="/static",app=staticfiles.StaticFiles(directory="./static"), name="static")

#错误处理
@app.exception_handler(StarletteHTTPException)
async def handler_http_exception(request,exc:StarletteHTTPException):
    return PlainTextResponse(content=str(exc.detail),status_code=exc.status_code)

@app.exception_handler(RequestValidationError)
async def handler_validation_error(request,exc):
    return PlainTextResponse(content=str(exc), status_code=400)

app.include_router(app01,prefix="/chapter01",tags=["第一章 请求参数验证"])
app.include_router(app02,prefix="/chapter02",tags=["第二章 Cookie&Header"])
app.include_router(app03,prefix="/chapter03",tags=["第三章 响应模型"])
app.include_router(app04,prefix="/chapter04",tags=["第四章 表单"])
app.include_router(app05,prefix="/chapter05",tags=["第五章 文件上传"])
app.include_router(app06,prefix="/chapter06",tags=["第六章 错误处理"])
app.include_router(app07,prefix="/chapter07",tags=["第七章 依赖注入"])

if __name__ == "__main__":
    #workers 制定进程数
    uvicorn.run("main:app",host="0.0.0.0",port=8000, reload=True, workers=1)